package com.kingzoder.food.exception;

import com.kingzoder.food.common.AppHttpCode;
import com.kingzoder.food.common.base.ResultVO;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.servlet.NoHandlerFoundException;

import java.nio.file.AccessDeniedException;

import static com.kingzoder.food.common.AppHttpCode.ERROR_PARAM;


/**
 * @author 轩辕铮
 */
@Slf4j(topic = "全局异常处理")
@RestControllerAdvice
public class RRExceptionHandler {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 处理自定义异常
     */
    @ExceptionHandler(RRException.class)
    public ResultVO handleRRException(RRException e) {
        return ResultVO.error(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(NoHandlerFoundException.class)
    public ResultVO handlerNoFoundException(Exception e) {
        e.printStackTrace();
        logger.error(e.getMessage(), e);
        return ResultVO.error(404, "路径不存在，请检查路径是否正确");
    }


    @ExceptionHandler(HttpClientErrorException.Unauthorized.class)
    public ResultVO handleAuthorizationException(HttpClientErrorException.Unauthorized e) {
        e.printStackTrace();
        logger.error(e.getMessage(), e);
        return ResultVO.error("没有权限，请联系管理员授权");
    }

    @ExceptionHandler(AccessDeniedException.class)
    public ResultVO handleAuthorizationException(AccessDeniedException e) {
        e.printStackTrace();
        logger.error(e.getMessage(), e);
        return ResultVO.error(AppHttpCode.ACCESS_DENIED.getCode(), AppHttpCode.ACCESS_DENIED.getMessage());
    }

//    @ExceptionHandler(ExpiredJwtException.class)
//    public ResultVO handleExpiredJwtException(ExpiredJwtException e) {
//        e.printStackTrace();
//        logger.error(e.getMessage(), e);
//        return ResultVO.error(AppHttpCode.LOGIN_ERROR.getCode(), AppHttpCode.LOGIN_ERROR.getMessage());
//    }

    @ExceptionHandler(Exception.class)
    public ResultVO handleException(Exception e) {
        e.printStackTrace();
        log.error("未知错误");
        return ResultVO.error("系统繁忙");
    }


    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ResultVO methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        log.error(e.getMessage(), e);
        ObjectError objectError = e.getBindingResult().getAllErrors().stream().findFirst().get();
        return ResultVO.error(ERROR_PARAM.getCode(), objectError.getDefaultMessage());
    }

    @ExceptionHandler(value = ConstraintViolationException.class)
    public ResultVO constraintDeclarationExceptionHandler(ConstraintViolationException e) {
        log.error(e.getMessage(), e);
        ConstraintViolation<?> constraintViolation = e.getConstraintViolations().stream().findFirst().get();
        return ResultVO.error(ERROR_PARAM.getCode(), constraintViolation.getMessage());
    }

//    @ExceptionHandler(value = BadCredentialsException.class)
//    public ResultVO badCredentialsExceptionHandler(ConstraintViolationException e) {
//        log.error(e.getMessage(), e);
//        ConstraintViolation<?> constraintViolation = e.getConstraintViolations().stream().findFirst().get();
//        return ResultVO.error(AppHttpCode.LOGIN_ERROR.getCode(), constraintViolation.getMessage());
//    }

    @ExceptionHandler(value = MissingServletRequestParameterException.class)
    public ResultVO missingServletRequestParameterExceptionHandler(MissingServletRequestParameterException e) {
        e.printStackTrace();
        return ResultVO.error("系统繁忙");
    }

    @ExceptionHandler(value = IllegalStateException.class)
    public ResultVO illegalStateExceptionHandler(IllegalStateException e) {
        e.printStackTrace();
        return ResultVO.error("系统繁忙");
    }

    @ExceptionHandler(value = BindException.class)
    public ResultVO bindExceptionHandler(BindException e) {
        e.printStackTrace();
        log.error(e.getMessage(), e);
        FieldError fieldError = e.getBindingResult().getFieldErrors().stream().findFirst().get();
        return ResultVO.error(ERROR_PARAM.getCode(), fieldError.getDefaultMessage());
    }


    @ExceptionHandler(value = ResponseStatusException.class)
    public ResultVO responseStatusExceptionHandler(ResponseStatusException e) {
        log.error(e.getMessage(), e);
        throw e;
    }

    //-------------------------------SQL--------------------------------
//    @ExceptionHandler(DuplicateKeyException.class)
//    public ResultVO<String> handleDuplicateKeyException(DuplicateKeyException e) {
//        logger.error("唯一索引冲突", e);
//        // 从异常中获取原始SQL错误信息
//        Throwable rootCause = e.getRootCause();
//        String errorMessage = rootCause != null ? rootCause.getMessage() : e.getMessage();
//        // 冲突值
//        String conflictValue = RegexUtils.extractSQLConflictValue(errorMessage);
//        return ResultVO.error(ERROR_PARAM.getCode(), conflictValue + "已经存在系统中，请重新设置！");
//    }
}
